import React from 'react'
import {connect,} from 'react-redux'
import {withRouter,} from 'react-router-dom'
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";
import LocalStorageService from "../../utils/LocalStorageService";
import {GiftMapper} from "../../utils/constants";
import {buyGameAiReq, buyGiftReq, getMyGiftReq} from "../../apis/goApis";
import {WhiteSpace, Modal, Toast,} from "antd-mobile";
import GiftItem from "../game-room/components/Main/chat-room/GiftItem/GiftItem";
import SmallCoin from "../../res/images/web/shared/coin.png";
import './gift-shop-item.css'
import GiftCount from "../game-room/components/Main/chat-room/GiftPopup/GiftCount/GiftCount";

const storage = LocalStorageService

class Gift extends React.Component {
    constructor(props) {
        super(props)
        this.uid = storage.get('userid')
        this.state = {
            list: [],
            myGiftList: [],
            selectGift: {},
            count: 0,
            popUp: {
                buy: false,
            }
        }
    }

    componentDidMount() {
        this.getUserDetail()
            .then(() => {
                this.getMyGift()
            })
    }

    getUserDetail = () => {
        const userDetail = this.props.user.userdetail
        if (userDetail.initFlag === 0) {
            return this.props.fetchUserDetail({uid: this.uid,})
        } else {
            return Promise.resolve(true)
        }
    }

    getMyGift = () => {
        getMyGiftReq({
            uid: this.uid,
        }).then((resp) => {
            const data = resp.data
            const list = data.prop.sort((g1, g2) => g1.Gold - g2.Gold)
            const myGiftList = data.packet
            this.setState({
                list,
                myGiftList,
            })
        })
    }

    callBuyModal = (gift) => {
        this.setState({
            selectGift: gift,
        }, () => {
            this.setState({
                popUp: {
                    ...this.state.popUp,
                    buy: true,
                }
            })
        })
    }

    onBuyModalClose = () => {
        this.setState({
            popUp: {
                ...this.state.popUp,
                buy: false,
            }
        }, () => {
            this.setState({
                selectGift: {},
                count: 0,
            })
        })
    }

    buyGift = (gift) => {
        // 8.apis/buyprop //买道具
        // type BuyPropJson struct {
        //     uid    string  //用户uid
        //     propid int     //道具id
        //     count  int     //购买数量
        // }
        const params = {
            uid: this.uid,
            propid: gift.Id,
            count: this.state.count,
        }
        buyGiftReq(params)
            .then((res) => {
                if (res.data.ok === 1) {
                    Toast.success('购买成功', 1)
                    setTimeout(() => {
                        this.getMyGift()
                        this.props.fetchUserDetail({uid: this.uid,})
                    }, 1000)
                } else if (res.data.err === 60008) {
                    Toast.fail('金币不足', 1)
                }
            })
    }

    updateCount = (int) => {
        const newCount = this.state.count + int
        if (newCount < 0) return
        this.setState({
            count: newCount,
        })
    }

    render() {
        const my = this.state.myGiftList
        const list = this.state.list
        const myGold = this.props.user.userdetail.Gold
        const g = this.state.selectGift
        const empty = this.state.count === 0
        const totalPrice = g.Gold * this.state.count
        const cantBuy = myGold < totalPrice
        const buttonDisabled = empty || cantBuy

        const myTemplate = <div>
            <p>我的背包</p>
            <WhiteSpace />
            <div className="flex flex-wrap-container">
                {my && my.map(gift => {
                    const id = gift[0]
                    // const giftData = GiftMapper[giftId]
                    let giftData
                    if (list) {
                        giftData = list.find(g => g.Id === id)
                    }
                    const count = gift[1]
                    if (giftData) {
                        return <GiftItem
                            key={id}
                            gift={{
                                ...giftData,
                                count,
                            }}
                        />
                    }
                    return null
                })}
            </div>
        </div>

        const giftTemplate = <div>
            <div className='flex-space-between-align-center'>
                <p>礼物兑换</p>
                <p className='gray-text'>我的金币 <span style={{color: '#FFA500',}}>{myGold}</span></p>
            </div>
            <WhiteSpace />
            <div className="flex-space-between-align-center flex-wrap-container">
                {list.map(gift => {
                    const srcId = `gift_${gift.Id}`
                    const iconSrc = GiftMapper[srcId].src
                    return <div className='gift-shop-item' key={srcId}>
                        {/*<img src={iconSrc} alt=''/>*/}
                        <div style={{width: '100%', height: '120px',}}>
                            <img src={iconSrc} alt='' style={{height: gift.Id === 9 ? '100px' : '120px', width: '120px',}}/>
                        </div>
                        <div className="flex-space-between-align-center" style={{padding: '8px',}}>
                            <div>
                                <p style={{marginBottom: '4px',}}>{gift.Name}</p>
                                <div className='flex-align-center'>
                                    <img src={SmallCoin} alt='' style={{marginRight: '4px',}}/>
                                    <p style={{color: '#FFA500',}}>{gift.Gold}</p>
                                </div>
                            </div>
                            <button
                                className='gift-shop-buy-button'
                                // onClick={() => this.buyGift(gift)}
                                onClick={() => this.callBuyModal(gift)}
                            >兑换</button>
                        </div>
                    </div>
                })}
            </div>
        </div>

        const buyModal = <Modal
            popup
            visible={this.state.popUp.buy}
            animationType="slide-up"
            onClose={this.onBuyModalClose}
        >
            <div
                className='gift-shop-buy-modal'
            >
                <p className='gift-shop-buy-modal-title'>礼物兑换</p>

                <div className='flex-align-center'>
                    <div className='gift-shop-buy-modal-img'>
                        <img alt='' src={GiftMapper[`gift_${g.Id}`]?.src} />
                    </div>
                    <div className='flex-space-between flex-wrap-container gift-shop-buy-modal-detail'>
                        <p className='gift-shop-buy-modal-detail-name'>{g.Name}</p>
                        <div className='flex-space-between-align-center' style={{width: '100%',}}>
                            <p>价值</p>
                            <div className='flex-align-center'>
                                <img src={SmallCoin} alt='' style={{marginRight: '4px',}}/>
                                <p style={{color: '#FFA500', fontSize: 20,}}>{g.Gold}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <GiftCount
                    changeTotal={this.updateCount}
                    total={this.state.count}
                />
            </div>
            <div className='flex-align-center'>
                <div className='gift-shop-buy-modal-bottom-total flex-align-center'>
                    <p>合计：</p>
                    <div className='flex-align-center'>
                        <img src={SmallCoin} alt='' style={{marginRight: '4px',}}/>
                        <p style={{color: '#FFA500', fontSize: 20,}}>{g.Gold * this.state.count}</p>
                    </div>
                </div>
                <button
                    className={
                        buttonDisabled
                            ? 'gift-shop-buy-modal-bottom-button gift-shop-buy-modal-bottom-button-disabled'
                            : 'gift-shop-buy-modal-bottom-button'
                    }
                    onClick={buttonDisabled
                        ? () => {}
                        : () => this.buyGift(g)
                    }
                >
                    {cantBuy ? '金币不足' : '立即兑换'}
                </button>
            </div>

        </Modal>

        return <>
            {buyModal}
            <GoBackLayout
                history={this.props.history}
                mainTitle='礼物'
            >
                <div style={{padding: '16px',}}>
                    {myTemplate}
                    <WhiteSpace size='xl'/>
                    {giftTemplate}
                </div>
            </GoBackLayout>
        </>
    }

}

const mapState = (state) => ({
    user: state.user,
})

const mapDispatch = (dispatch) => ({
    fetchUserDetail: (payload) => dispatch.user.fetchUserDetail(payload)
})

export default connect(mapState, mapDispatch)(withRouter(Gift))
// 7. apis/buyproppage //买道具页面
// type BuyPropPageJson struct{
//     uid string
// }
//
// resp:
// {
//     ok     int
//     packet [][]int
//     prop   []gifts
// }
//
// type gifts struct{
//     Id        int
//     Name      string
//     Gold      int64
// }
//


